package jetbrains.buildServer.cuta.logic;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;



/**
 * @author Leonid Bushuev from JetBrains
 */

public class CutaMainTab
{

    @NotNull
    final String name;

    @NotNull
    private String myId;

    @Nullable
    private PageDef myPage;



    private final Map<String,CutaSubTab> mySubTabs =
            new LinkedHashMap<String,CutaSubTab>();

    private final Collection<CutaSubTab> mySubTabsForVisitors =
            Collections.unmodifiableCollection(mySubTabs.values());


    public CutaMainTab(final @NotNull String name)
    {
        this.name = name;
        myId = "zero";
    }


    @NotNull
    public String getId()
    {
        return myId;
    }


    /**
     * Tab name (what will be shown on the tab).
     * @return the tab name.
     */
    @NotNull
    public String getName()
    {
        return name;
    }


    @NotNull
    public PageDef getFirstPage()
    {
        if (myPage != null)
            return myPage;

        if (!mySubTabs.isEmpty())
            return mySubTabs.values().iterator().next().getPage();

        throw new IllegalStateException("Tab " + getName() + " has no pages!");
    }


    @Nullable
    public PageDef getPage()
    {
        return myPage;
    }


    public void setPage(@Nullable PageDef page)
    {
        this.myPage = page;

        if (page != null)
            this.myId = page.id;
        else
            updateIdFromTheFirstPage();
    }


    public void addSubTab(@NotNull CutaSubTab subTab)
    {
        mySubTabs.put(subTab.getName(), subTab);
        if (mySubTabs.size() == 1)
            updateIdFromTheFirstPage();
    }


    private void updateIdFromTheFirstPage()
    {
        if (mySubTabs.isEmpty())
            myId = "zero";
        else
            myId = mySubTabs.values().iterator().next().getId();
    }


    public int getSubTabCount()
    {
        return mySubTabs.size();
    }


    public Collection<CutaSubTab> getSubTabs()
    {
        return mySubTabsForVisitors;
    }


    @Nullable
    public PageDef getSubPageById(String id)
    {
        for (CutaSubTab subTab: mySubTabs.values())
            if (subTab.getId().equals(id))
                return subTab.getPage();
        return null;
    }

}
